const { Pool } = require('pg');
require('dotenv').config({ path: '../backend/.env' });

// Database configuration from environment variables
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  password: process.env.DB_PASSWORD,
  port: process.env.DB_PORT,
});

async function checkDatabase() {
  let client;
  try {
    // Connect to the database
    client = await pool.connect();
    console.log('Connected to the PostgreSQL server successfully');

    // Check existing roles
    const rolesResult = await client.query('SELECT rolname FROM pg_roles;');
    console.log('Existing roles:');
    rolesResult.rows.forEach(row => {
      console.log('  -', row.rolname);
    });

    // Check if financeapp database exists
    const dbResult = await client.query("SELECT datname FROM pg_database WHERE datname = 'financeapp';");
    if (dbResult.rows.length > 0) {
      console.log('Database "financeapp" already exists');
    } else {
      console.log('Database "financeapp" does not exist');
    }

    client.release();
    await pool.end();
  } catch (error) {
    console.error('Error checking database:', error.message);
    if (client) {
      client.release();
    }
    await pool.end();
  }
}

// Run the check
checkDatabase();